package ex0;

import ex0.expressions.Expression;
import ex0.expressions.ExpressionFactory;
import ex0.expressions.ExpressionFactoryImpl;

import java.util.EmptyStackException;
import java.util.Stack;



public class Calc {

	public class State {
		public Stack<Double> valueStack = new Stack<Double>();
		public Stack<String> infixExpStack = new Stack<String>();
		boolean isError = false;
	}
	
	private State state;
    private ExpressionFactory expressionFactory;
	
	public Calc() {
		state = new State();
        expressionFactory = new ExpressionFactoryImpl(state);
	}
	
	public State process(String expression) {
		for (String tok : expression.split(" ")) {
			if (state.isError)
				return state;
			
			processToken(tok);
		}

		state.isError = state.valueStack.size() > 1 ? true : state.isError;
		return state;
	}
	
	void processToken(String token) {
		try {
            if (token.length() == 0) {
                return;
            }

            Expression expression = expressionFactory.createExpression(token);
            if(expression == null) {
                state.isError = true;
            }
            else {
                state.valueStack.push(expression.evaluate());
                state.infixExpStack.push(expression.toStr());
            }
		}
		catch (EmptyStackException e) {
			state.isError = true;
		}
	}
}

